package com.apache.ius.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apache.database.exception.DaoAccessException;

import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
  * description:  抽象代理manager实现
  */
public class IusProxyManagerImpl implements ProxyManager {

	private Logger log = LoggerFactory.getLogger(getClass());
	protected Map<String, List<PluginConnector>> plugins = new HashMap<String, List<PluginConnector>>();

	public void setPlugins(Map<String, List<PluginConnector>> plugins) {
		this.plugins = plugins;
	}

	/**
	  * description:代理执行方法(带事务)
	  * @param vo 方法参数
	  * @return 
	  */
	public Object saveInvoke(ParamsVo vo) throws BusinessException {
		String key = vo.getKey();
		if (!Validator.isEmpty(plugins) && !Validator.isEmpty(plugins.get(key))) {
			Object result = null;
			try {
				for (PluginConnector plugin : plugins.get(key)) {
					result = plugin.execute(vo);
				}
			} catch (Exception e) {
				log.error("异常",e);
				if(e instanceof DaoAccessException){
					throw new BusinessException("执行出错:"+e.getMessage());
				} else {
					throw new BusinessException("执行出错", e);
				}
			}
			return result;
		}
		return null;
	}

	/**
	  * description:代理执行方法(不带事务)
	  * @param vo 方法参数
	  * @return 
	  */
	public Object doInvoke(ParamsVo vo) throws BusinessException {
		String key = vo.getKey();
		if (!Validator.isEmpty(plugins) && !Validator.isEmpty(plugins.get(key))) {
			Object result = null;
			try {
				for (PluginConnector plugin : plugins.get(key)) {
					result = plugin.execute(vo);
				}
			} catch (Exception e) {
				log.error("异常",e);
				if(e instanceof DaoAccessException){
					throw new BusinessException("执行出错:"+e.getMessage());
				} else {
					throw new BusinessException("执行出错", e);
				}
			}
			return result;
		}
		return null;
	}

}
